// 对模型添加实例方法
const instancesExtend = {
    extendModel: function(model, attr, modelExt) {
        // 获得修改的属性列
        model.prototype.getUpdateFields = function() {
            var chs = this.changed();
            if (chs == null || chs.length == 0) {
                return chs;
            }
            var rtObj = { 'fields': [] };
            for (var i = 0; i < chs.length; i++) {
                if (modelExt.updates.indexOf(chs[i]) != -1) {
                    rtObj.fields.push(chs[i]);
                }
            }
            return rtObj;
        };
        // 可以将原始方法修改名称
        //model.prototype.saveData = model.prototype.save;

        // 扩展的update方法,只更新可以修改的字段中数据变化的属性
        model.prototype._update = async function() {
            this.isNewRecord = false;
            return this.save(this.getUpdateFields());

            //return this.update(this.getUpdateFields());
        };

        // 扩展的update方法,只更新可以修改的字段中数据变化的属性
        model.prototype.setPropertysByUpdates = function(obj) {
            for (var i = 0; i < modelExt.updates.length; i++) {
                var propertyName = modelExt.updates[i];
                if (obj[propertyName]) {
                    this[propertyName] = obj[propertyName];
                }
            }
        }

        // 设置创建人创建时间 修改人 修改时间
        model.prototype.setPropertys = function(userInfo) {
            this.creator = userInfo.loginName;
            this.cretaeDate = new Date();
            this.modifier = userInfo.loginName;
            this.lastUpdatedDate = new Date();
        }

        // 设置 修改人 修改时间
        model.prototype.setPropertysByUpDate = function(userInfo) {
            this.modifier = userInfo.loginName;
            this.lastUpdatedDate = new Date();
        }


        // 根据唯一编码来判断对象是否存在
        model.prototype.isExists = async function() {

            var akNameArray = model.akNameArray();
            console.log(akNameArray);
            // 组装where子句
            //console.log(akNameArray);
            const queryCondition = {
                "where": {}
            }
            for (var i = 0; i < akNameArray.length; i++) {
                queryCondition.where[akNameArray[i]] = this.getDataValue(akNameArray[i]);
            }
            return model.count(queryCondition);
        };

        // 获得唯一编码的值(数组)
        model.prototype.getAkValue = function() {
            var akNameArray = model.akNameArray();
            var arr = [];
            for (var i = 0; i < akNameArray.length; i++) {
                arr.push(this.getDataValue(akNameArray[i]));
            }
            return arr;
        };

        model.prototype.getTransData = function(dataSendLog, msg) {
            return this.get({ plain: true });
        }
    }
};



module.exports = instancesExtend;